import { Reducer } from 'redux';
import {queryList} from '@/services/region';
import {Effect} from "dva";
import {ConnectState} from "@/models/connect";
import { OptionType } from '@/types/common';

export interface RegionStateType {
  list:OptionType[]
}

export interface RegionModelType {
  namespace: 'region';
  state: RegionStateType;
  effects: {
    queryProvince:Effect;
    queryCity:Effect;
    queryDistrict:Effect;
  };
  reducers: {
    changeList:Reducer<RegionStateType>
  };
}
const RegionModel: RegionModelType = {
  namespace: 'region',
  state:{
    list:[]
  },
  effects:{
    *queryProvince(_, { call, put,select }) {
      const list:OptionType[] = yield select(
        (state: ConnectState) => state.region.list,
      );
      if(list.length>0){
        return ;
      }
      const {data} = yield call(queryList);
      yield put({
        type: 'changeList',
        payload: data.map((item:OptionType)=>{return {...item,isLeaf: false,type:'provinceId'}})
      });
    },
    *queryCity({payload}, { call, put,select }) {
      let list:OptionType[] = yield select(
        (state: ConnectState) => state.region.list,
      );
      if (!payload[0])return;

      const index=list.findIndex(item=>item.id===payload[0]);
      let province=list[index];
      if(province.children&&province.children.length>0){
        return ;
      }

      const {data} = yield call(queryList,payload[0]);
      province.children=data.map((item:OptionType)=>{return {...item,isLeaf: false,type:'cityId'}});
      list[index]=province;
      yield put({
        type: 'changeList',
        payload: [...list],
      });
    },
    *queryDistrict({payload}, { call, put,select }) {
      let list:OptionType[] = yield select(
        (state: ConnectState) => state.region.list,
      );
      if (!payload[0])return;
      const provinceIndex=list.findIndex(item=>item.id===payload[0]);


      if (!payload[1])return;
      let province=list[provinceIndex];
      const cityIndex=province.children?.findIndex(item=>item.id===payload[1]);
      // @ts-ignore
      let city=province.children[cityIndex];
      if(city.children&&city.children.length>0){
        return ;
      }

      const {data} = yield call(queryList,payload[1]);
      city.children=data.map((item:OptionType)=>{return {...item,isLeaf: true,type:'districtId'}});
      // @ts-ignore
      province[cityIndex]=city;
      list[provinceIndex]=province;
      yield put({
        type: 'changeList',
        payload: [...list],
      });
    },
  },
  reducers: {
    changeList(state, { payload }) {
      return {
        ...state,
        list: payload||[],
      };
    },
  }
};
export default RegionModel;
